#include "widget.h"
#include "ui_widget.h"
#include "tperson.h"
#include <QSpinBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , boy(nullptr)
    , girl(nullptr)
    , spinBoy(nullptr)
    , spinGirl(nullptr)
{
    ui->setupUi(this);

    boy = new TPerson("小明", this);
    girl = new TPerson("小红", this);

    girl->setAge(20);

    boy->setProperty("sex", "boy");
    girl->setProperty("sex", "girl");

    spinBoy = ui->setboy;
    spinGirl = ui->setgirl;

    // 为 spinBox 添加自定义属性
    spinBoy->setProperty("isBoy", true);
    spinGirl->setProperty("isBoy", false);

    // 信号与槽连接
    connect(boy, SIGNAL(ageChanged(int)),spinBoy, SLOT(setValue(int)));
    connect(girl, SIGNAL(ageChanged(int)),spinGirl , SLOT(setValue(int)));
    connect(boy, SIGNAL(ageChanged(int)), this, SLOT(do_ageChanged(int)));
    connect(girl, SIGNAL(ageChanged(int)), this, SLOT(do_ageChanged(int)));
    connect(spinBoy, SIGNAL(valueChanged(int)), this, SLOT(do_spinChanged(int)));
    connect(spinGirl, SIGNAL(valueChanged(int)), this, SLOT(do_spinChanged(int)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_clear_clicked()
{
    ui->plainTextEdit->clear();
}


void Widget::on_boy_add_clicked()
{
    boy->incAge();
}


void Widget::do_ageChanged(int value)
{
    TPerson *person = qobject_cast<TPerson*>(sender());
    Q_UNUSED(person)

    QString str = QString("%1,%2,年龄 = %3")
                      .arg(person->property("name").toString())
                      .arg(person->property("sex").toString())
                      .arg(value);
    ui->plainTextEdit->appendPlainText(str);
}

void Widget::do_spinChanged(int arg1)
{
    QSpinBox *spinBox = qobject_cast<QSpinBox*>(sender());
    if(spinBox->property("isBoy").toBool())
        boy->setAge(arg1);
    else
        girl->setAge(arg1);
}


void Widget::on_show_info_clicked()
{
    QString info = QString("%1: 年龄=%2, 分数=%3\n%4: 年龄=%5, 分数=%6")
                       .arg(boy->property("name").toString())
                       .arg(boy->age())
                       .arg(boy->property("score").toInt())
                       .arg(girl->property("name").toString())
                       .arg(girl->age())
                       .arg(girl->property("score").toInt());
    ui->plainTextEdit->appendPlainText(info);
}


void Widget::on_girl_add_clicked()
{
    girl->incAge();
}


void Widget::on_setboy_textChanged(const QString &arg1)
{

}

